import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    // set page title
    document.title = getPageTitle(to.meta.title)
    const hasToken = getToken()
    if ( hasToken ) {
      if ( to.path === '/login' ) {
        next({path: '/'})
        NProgress.done()
      } else {

        const hasGetUserInfo = store.state.user.group_title
        if ( hasGetUserInfo ) {
          next()
        } else {
          try {
            await store.dispatch('user/getInformations')// 拉取用户信息
            //异步路由加入404
            store.getters.routers.push({
              path: '*',
              redirect: '/404'
            })
            router.addRoutes(store.getters.routers)//添加后台路由表
            /* store.commit('SET_NAME', res.data.admin_username)*/
            next({...to, replace: true})
          } catch (error) {
            // 如果出错了，把令牌去掉，并让用户重新去到登录页面
            //await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            //关闭进度条
            NProgress.done()
          }
        }
      }
    } else {
      if ( whiteList.indexOf(to.path) !== -1 ) {
        next()
      } else {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
)

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
